
package cn.zkdcloud.framework.handler;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import cn.zkdcloud.framework.servlet.HttpContext;
import cn.zkdcloud.framework.util.Proty;

import java.io.IOException;
import java.util.Iterator;

/**
 * @author zk
 * @version  2017/6/18.
 */
public class StaticResourcesHandler extends AbstractHandler {


    /**
     * defalut servlet operator static resources
     */
    private static final String DEFAULT_SERVELT = "default";

    /** default servlet by jetty ,tomcat,jboss...
     *
     */
    private RequestDispatcher requestDispatcher;


    public StaticResourcesHandler(ServletContext servletContext){
        this.requestDispatcher = servletContext.getNamedDispatcher(DEFAULT_SERVELT);
    }

    /**handler method
     *
     * @param httpContext httpContext
     * @param it it
     */
    public void handler(HttpContext httpContext,Iterator<Handler> it) {
        try {
            if(isStaticPath(httpContext.getRequest())){
                requestDispatcher.forward(httpContext.getRequest(),httpContext.getResponse());
                return;
            }
        } catch (ServletException e) {
            System.out.println("this request is not static resources");
        } catch (IOException e) {
            System.out.println("this request is not static resources");
        }

        if(it.hasNext()){
            it.next().handler(httpContext,it);
        }
    }

    /** isStaticRequest
     *
     * @param request HttpServletRequest
     * @return boolean
     */
    public boolean isStaticPath(HttpServletRequest request){
        String path = request.getRequestURI();
        return Proty.StaticResources.isStaticPath(path);
    }
}
